﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using StyleMVVM.DependencyInjection;
using StyleMVVM.DependencyInjection.Impl;

namespace StyleMVVM.MVC.Extensions
{
	public class InjectionModelBinder : DefaultModelBinder
	{
		private IDependencyInjectionContainer container;

		public InjectionModelBinder(IDependencyInjectionContainer container)
		{
			this.container = container;
		}

		protected override object CreateModel(ControllerContext controllerContext,
		                                      ModelBindingContext bindingContext,
		                                      Type modelType)
		{
			object returnObject = container.LocateByType(modelType);

			if (returnObject == null)
			{
				AttributedExportStrategy exportStrategy = new AttributedExportStrategy(new[] { modelType.FullName }, modelType);

				exportStrategy.ExportedTypes = new List<Type> { modelType };

				container.AddStrategy(exportStrategy);

				returnObject = exportStrategy.Activate(container.CreateInjectionContext(), null);
			}

			return returnObject;
		}
	}
}